using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreateTerrain
{
    Terrain[] terrains = new Terrain[4];
    Texture2D heightMap;
    float maxHeight;

    public void GetTerrainHeight()
    {
        int terrainNum = terrains.Length;
        int splitNumX = 2;
        int heightSize = (int)terrains[0].terrainData.size.x;
        if (!Mathf.IsPowerOfTwo(heightSize))
        {
            Debug.LogError("heightSize is not PowerOfTwo");
            return;
        }

        var realHeightSize = Mathf.NextPowerOfTwo(heightSize);
        int totalHeightSize = realHeightSize * terrainNum / splitNumX;
        float[] pixelData = new float[totalHeightSize * totalHeightSize];
        heightMap = new Texture2D(totalHeightSize, totalHeightSize, TextureFormat.RFloat, false);
        maxHeight = terrains[0].terrainData.heightmapScale.y;

        for (int i = 0; i < terrainNum; i++)
        {
            var terrain = terrains[i];
            var offsetX = (i % splitNumX) * heightSize;
            var offsetY = (i / splitNumX) * heightSize;
            for (int j = 0; j < heightSize; j++)
            {
                for (int k = 0; k < heightSize; k++)
                {
                    pixelData[offsetX + i + (j + offsetY) * totalHeightSize] = terrain.terrainData.GetHeight(i, j) / maxHeight;
                }
            }
        }

        heightMap.SetPixelData(pixelData, 0); 
        heightMap.Apply();
    }

/*    private Mesh CreateQuadMesh(int szie, float gridSize = 1)
    {
        _gValue._PerPatchGridNum
    }*/
}
